import React from 'react';
import _ from 'lodash';
import router from 'umi/router';
import { TextWithTags, NumberView } from '@/components/BaseTable';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    const x = value;
    if (x.pid === pid) {
      if (hasChildren(list, x)) {
        x.children = [];
        x.children = buildTree(list, x.id);
      }
      tree.push(x);
    }
  });
  return tree;
};

export const levelTree = (list, level) => {
  const cloneList = _.cloneDeep(list);
  let filterItem = [];
  if (level === 'region') {
    filterItem = _.filter(
      cloneList,
      v => v.type === 'org_wanda_group' || v.type === 'org_business_division',
    );
  }
  if (level === 'cityCompany') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.type === 'org_wanda_group' ||
        v.type === 'org_business_division' ||
        v.type === 'org_city_company',
    );
  }
  if (level === 'project') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.type === 'org_wanda_group' ||
        v.type === 'org_business_division' ||
        v.type === 'org_city_company' ||
        v.type === 'org_project',
    );
  }
  if (level === 'stage') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.type === 'org_wanda_group' ||
        v.type === 'org_business_division' ||
        v.type === 'org_city_company' ||
        v.type === 'org_project' ||
        v.type === 'org_stage',
    );
  }
  return filterItem;
};

export const getArrayNumbers = (text, division = 1) => {
  if (!_.isEmpty(text) && text.indexOf('/') > -1) {
    // text.split('/')
    const temp = [];
    _.forEach(text.split('/'), value => {
      temp.push((_.trim(value) * 1) / division);
    });
    text = temp;
  } else {
    text = (text * 1) / division;
  }

  return text;
};

export const setFixedColumns = (fixedColumns, item, attributesCheckeds) => {
  _.each(item.children, v => {
    if (_.indexOf(attributesCheckeds, '套数') > -1) {
      fixedColumns.push({
        key: `${v.key}-Num`,
        dataKey: `${v.key}-Num`,
        title: '',
        width: 180,
        align: 'right',
        headerRenderer: () => (
          <HeaderRenderer type={1}>
            <div>套数/车位数</div>
            <div>(套/个)</div>
          </HeaderRenderer>
        ),
        dataGetter: ({ rowData }) => {
          let val = '';
          if (item.monthKey !== 'firstMonthlyValue' && item.monthKey !== 'secondMonthlyValue') {
            val = [
              rowData[item.monthKey][v.monthKey].roomNum * 1,
              rowData[item.monthKey][v.monthKey].parkingNum * 1,
            ];
          }
          if (item.monthKey === 'firstMonthlyValue' || item.monthKey === 'secondMonthlyValue') {
            const filterData = _.filter(rowData[item.monthKey], x => x.yearMonth === item.key)[0];
            val = [filterData[v.monthKey].roomNum * 1, filterData[v.monthKey].parkingNum * 1];
          }
          return val;
        },
        cellRenderer: <NumberView precision={0} />,
      });
    }
    if (_.indexOf(attributesCheckeds, '面积') > -1) {
      fixedColumns.push({
        key: `${item.key + v.key}area`,
        dataKey: `${item.key + v.key}area`,
        title: '',
        width: 180,
        align: 'right',
        headerRenderer: () => (
          <div>
            <div>面积</div>
            <div>(平米)</div>
          </div>
        ),
        dataGetter: ({ rowData }) => {
          let val = '';
          if (item.monthKey !== 'firstMonthlyValue' && item.monthKey !== 'secondMonthlyValue') {
            val = [rowData[item.monthKey][v.monthKey].saleArea * 1];
          }
          if (item.monthKey === 'firstMonthlyValue' || item.monthKey === 'secondMonthlyValue') {
            const filterData = _.filter(rowData[item.monthKey], x => x.yearMonth === item.key)[0];
            val = [filterData[v.monthKey].saleArea * 1];
          }
          return val;
        },
        cellRenderer: <NumberView precision={2} />,
      });
    }
    if (_.indexOf(attributesCheckeds, '均价') > -1) {
      fixedColumns.push({
        key: `${item.key + v.key}averagePrice`,
        dataKey: `${item.key + v.key}averagePrice`,
        title: '',
        width: 180,
        align: 'right',
        headerRenderer: () => (
          <HeaderRenderer type={2}>
            <div>均价</div>
            <div>(元/平米,个)</div>
          </HeaderRenderer>
        ),
        dataGetter: ({ rowData }) => {
          let val = '';
          if (item.monthKey !== 'firstMonthlyValue' && item.monthKey !== 'secondMonthlyValue') {
            val = [
              rowData[item.monthKey][v.monthKey].houseAvgPrice * 1,
              rowData[item.monthKey][v.monthKey].parkingAvgPrice * 1,
            ];
          }
          if (item.monthKey === 'firstMonthlyValue' || item.monthKey === 'secondMonthlyValue') {
            const filterData = _.filter(rowData[item.monthKey], x => x.yearMonth === item.key)[0];
            val = [
              filterData[v.monthKey].houseAvgPrice * 1,
              filterData[v.monthKey].parkingAvgPrice * 1,
            ];
          }
          return val;
        },
        cellRenderer: <NumberView precision={0} />,
      });
    }
    if (_.indexOf(attributesCheckeds, '金额') > -1) {
      fixedColumns.push({
        key: `${item.key + v.key}price`,
        dataKey: `${item.key + v.key}price`,
        title: '',
        width: 280,
        align: 'right',
        headerRenderer: () => (
          <HeaderRenderer type={3}>
            <div>金额</div>
            <div>(万元：合计/房源/车位)</div>
          </HeaderRenderer>
        ),
        dataGetter: ({ rowData }) => {
          let val = '';
          if (item.monthKey !== 'firstMonthlyValue' && item.monthKey !== 'secondMonthlyValue') {
            val = [
              rowData[item.monthKey][v.monthKey].housePrice / 10000 +
                rowData[item.monthKey][v.monthKey].parkingPrice / 10000,
              rowData[item.monthKey][v.monthKey].housePrice / 10000,
              rowData[item.monthKey][v.monthKey].parkingPrice / 10000,
            ];
          }
          if (item.monthKey === 'firstMonthlyValue' || item.monthKey === 'secondMonthlyValue') {
            const filterData = _.filter(rowData[item.monthKey], x => x.yearMonth === item.key)[0];
            val = [
              filterData[v.monthKey].housePrice / 10000 +
                filterData[v.monthKey].parkingPrice / 10000,
              filterData[v.monthKey].housePrice / 10000,
              filterData[v.monthKey].parkingPrice / 10000,
            ];
          }
          return val;
        },
        cellRenderer: <NumberView precision={0} />,
      });
    }
  });
  return fixedColumns;
};

export const getFixedColumns = (titleTree, attributesCheckeds) => {
  const fixedColumns = [];
  // 组织名
  fixedColumns.unshift({
    key: 'name',
    dataKey: 'name',
    title: '',
    width: 260,
    frozen: 'left',
    headerRenderer: () => <div>分期/组团/业态/楼栋</div>,
    dataGetter: ({ rowData }) => {
      if (rowData.type === 'org_project') {
        return (
          <a
            onClick={() => {
              router.push({
                pathname: '/common/supplyContrast',
                query: {
                  projectName: escape(rowData.name),
                  projectId: rowData.id,
                },
              });
            }}
          >
            {rowData.name}
          </a>
        );
      }
      return rowData.name;
    },
    // cellRenderer: <TextWithTags />,
  });

  _.each(titleTree, item => {
    if (!item.hidden) setFixedColumns(fixedColumns, item, attributesCheckeds);
  });
  return fixedColumns;
};

export const getTitleTree = (attributesCheckeds, currentYear, currentMonths) => {
  const titleTree = [
    {
      name: '组织/项目/分期',
      key: 'id',
      colspan: 1,
      rowspan: 4,
    },
    {
      // 年合计
      name: `${currentYear}年合计`,
      key: 'yearValue',
      monthKey: 'yearValue',
      rowspan: 1,
      hidden: !_.includes(currentMonths, '16'),
      children: [
        {
          name: '年初预算版',
          key: 'yearValue-budgetValue',
          monthKey: 'budgetValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '最新动态版',
          key: 'yearValue-dynamicValue',
          monthKey: 'dynamicValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '差异',
          key: 'yearValue-differenceValue',
          monthKey: 'differenceValue',
          colspan: 1 * attributesCheckeds.length,
        },
      ],
    },
  ];

  for (let i = 1; i <= 6; i += 1) {
    titleTree.push({
      name: `${currentYear}-0${i}`,
      key: `${currentYear}-0${i}`,
      monthKey: 'firstMonthlyValue',
      hidden: !_.includes(currentMonths, i.toString()),
      rowspan: 1,
      children: [
        {
          name: '年初预算版',
          key: `budgetValue-${currentYear}-0${i}`,
          monthKey: 'budgetValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '动态版',
          key: `dynamicValue-${currentYear}-0${i}`,
          monthKey: 'dynamicValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '差异',
          key: `differenceValue-${currentYear}-0${i}`,
          monthKey: 'differenceValue',
          colspan: 1 * attributesCheckeds.length,
        },
      ],
    });
  }

  titleTree.push(
    {
      name: '半年度对比',
      key: 'firstHalfYearValue',
      monthKey: 'firstHalfYearValue',
      rowspan: 1,
      hidden: !_.includes(currentMonths, '15'),
      children: [
        {
          name: '年初预算版',
          key: 'firstHalfYearValue-budgetValue',
          monthKey: 'budgetValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '供货实际',
          key: 'firstHalfYearValue-dynamicValue',
          monthKey: 'dynamicValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '差异',
          key: 'firstHalfYearValue-differenceValue',
          monthKey: 'differenceValue',
          colspan: 1 * attributesCheckeds.length,
        },
      ],
    },
    {
      name: '下半年计划',
      key: 'secondHalfYearValue',
      monthKey: 'secondHalfYearValue',
      rowspan: 1,
      hidden: !_.includes(currentMonths, '14'),
      children: [
        {
          name: '年中预算版',
          key: 'secondHalfYearValue-budgetValue',
          monthKey: 'budgetValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '最新动态版',
          key: 'secondHalfYearValue-dynamicValue',
          monthKey: 'dynamicValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '差异',
          key: 'secondHalfYearValue-differenceValue',
          monthKey: 'differenceValue',
          colspan: 1 * attributesCheckeds.length,
        },
      ],
    },
  );

  for (let i = 7; i <= 12; i += 1) {
    titleTree.push({
      name: i < 10 ? `${currentYear}-0${i}` : `${currentYear}-${i}`,
      key: i < 10 ? `${currentYear}-0${i}` : `${currentYear}-${i}`,
      monthKey: 'secondMonthlyValue',
      hidden: !_.includes(currentMonths, i.toString()),
      rowspan: 1,
      children: [
        {
          name: '年中预算版',
          key: i < 10 ? `budgetValue-${currentYear}-0${i}` : `budgetValue-${currentYear}-${i}`,
          monthKey: 'budgetValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '动态版',
          key: i < 10 ? `dynamicValue-${currentYear}-0${i}` : `dynamicValue-${currentYear}-${i}`,
          monthKey: 'dynamicValue',
          colspan: 1 * attributesCheckeds.length,
        },
        {
          name: '差异',
          key:
            i < 10 ? `differenceValue-${currentYear}-0${i}` : `differenceValue-${currentYear}-${i}`,
          monthKey: 'differenceValue',
          colspan: 1 * attributesCheckeds.length,
        },
      ],
    });
  }
  return titleTree;
};
